package cn.ac.iie.di.wx.handler;

import cn.ac.iie.di.commons.httpserver.framework.handler.HandlerI;
import cn.ac.iie.di.commons.httpserver.framework.util.ParseRequestStream;
import cn.ac.iie.di.wx.common.RuntimeEnv;
import cn.ac.iie.di.wx.httpservice.HttpSender;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.client.fluent.Content;
import org.apache.http.client.fluent.Response;
import org.apache.log4j.Logger;

/**
 *
 * @author Administrator
 */
public class WxPictureUrl implements HandlerI {

    static Logger logger = Logger.getLogger(WxPictureUrl.class.getName());

    public void execute(org.eclipse.jetty.server.Request pRequest, HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            byte[] bytesContent = new byte[2048];
            int bytesReadIn = 0;
            ServletOutputStream out = response.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(out);

            String urlStr = ParseRequestStream.parseRequestStreamAsString(pRequest.getInputStream());
            logger.info(urlStr);
            HttpSender hs = new HttpSender();
            if (RuntimeEnv.wxPictureUrlQueryLimit.incrementAndGet() <= Integer.parseInt((String) RuntimeEnv.getParam("wxPictureUrlQueryLimit"))) {
                RuntimeEnv.wxPictureUrlQueryCount.incrementAndGet();
                try {
                    String urlresult = hs.sendStringByUrl(urlStr, (String) RuntimeEnv.getParam("txUrl"));

                    if (!urlresult.equals("")) {
                        JSONObject urljSONObject = JSONObject.parseObject(urlresult);
                        String data = urljSONObject.getString("data");
                        if (!data.isEmpty()) {
                            JSONObject dldurljSONObject = JSONObject.parseObject(data);
                            String download_url = dldurljSONObject.getString("download_url");

                            InputStream responseIn = org.apache.http.client.fluent.Request.Get(download_url.replace("10.177.138.34", "10.238.3.12"))
                                    .execute().returnContent().asStream();
                            while ((bytesReadIn = responseIn.read(bytesContent, 0, 2048)) > 0) {
                                bos.write(bytesContent, 0, bytesReadIn);
                            }
                            bos.flush();
                            bos.close();
                            RuntimeEnv.wxPictureUrlQueryLimit.decrementAndGet();
                        }

                    }

                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            } else {
                InputStream inputStream = new ByteArrayInputStream("访问量超限".getBytes("UTF-8"));
                while ((bytesReadIn = inputStream.read(bytesContent, 0, 2048)) > 0) {
                    bos.write(bytesContent, 0, bytesReadIn);
                }
                bos.flush();
                bos.close();
                RuntimeEnv.wxPictureUrlQueryLimit.decrementAndGet();
            }

        } catch (Exception e) {
            logger.error("Filedownload send out error\n" + e.getMessage(), e);
        }
    }

    public void init() throws Exception {
    }
}
